package com.zhihuichongcheng.application.ui.mine;

import com.google.gson.Gson;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.FileUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.DepInfo;
import com.zhihuichongcheng.application.bean.mine.PositionInfo;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.glide.GlideCircleTransform;
import com.zhihuichongcheng.application.net.HttpCallback;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by 3water on 2016/10/29.
 */

public class UserInfoActivity extends BaseActivity implements View.OnClickListener {
    private TextView mTvDepartment, mTvPosition, mTvBJPhone, mTvTjPhone, mTvName, mTvMinPhone, mTvMaxPhone, mTvRemark;
    private String mUserId;
    private ImageView mImAvatar;
    private UserBean mUser;
    private TextView mTvRoomId;
    private String mUpdateIconCameraPath;
    private RelativeLayout mRlExit, mRlChangePassword;

    private View mDownloadList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initView();
        initData();
    }

    private void initView() {
        mTvRoomId = (TextView) findViewById(R.id.tv_roomId);
        mRlExit = (RelativeLayout) findViewById(R.id.rl_exit);
        mRlChangePassword = (RelativeLayout) findViewById(R.id.rl_change_password);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mImAvatar = (ImageView) findViewById(R.id.im_avatar);
        setTitle("我的");
        mTvDepartment = (TextView) findViewById(R.id.tv_department);
        mTvPosition = (TextView) findViewById(R.id.tv_position);
        mTvBJPhone = (TextView) findViewById(R.id.tv_bjphone);
        mTvTjPhone = (TextView) findViewById(R.id.tv_tjphone);
        mTvMinPhone = (TextView) findViewById(R.id.tv_minPhone);
        mTvMaxPhone = (TextView) findViewById(R.id.tv_maxPhone);
        mTvRemark = (TextView) findViewById(R.id.tv_remark);
        mDownloadList = findViewById(R.id.layout_download_list);

        mRlChangePassword.setOnClickListener(this);
        mImAvatar.setOnClickListener(this);
        mRlExit.setOnClickListener(this);
        mDownloadList.setOnClickListener(this);
    }

    private void initData() {
        mUser = app.getUser();
        //test
        DepInfo info = mUser.getDept();
        if (info != null) {
            mTvDepartment.setText(info.getDeptName());
        }
        PositionInfo positionInfo = mUser.getPosition();
        if (positionInfo != null) {
            mTvPosition.setText(positionInfo.getPositionName());
        }
        mTvRoomId.setText(mUser.getRoomId());
        mTvBJPhone.setText(mUser.getTianjinMobile());
        mTvTjPhone.setText(mUser.getTianjinMobile());
        Intent intent = getIntent();
        if (intent != null) {
            if (intent.hasExtra("userId")) {
                mUserId = intent.getStringExtra("userId");
            }
        }
        mTvMaxPhone.setText(mUser.getMaxPhone());
        mTvMinPhone.setText(mUser.getMinPhone());
        String remark = mUser.getRemark();
        if (!TextUtils.isEmpty(remark)) {
            mTvRemark.setText(mUser.getRemark());
        } else {
            mTvRemark.setText("没添加备注");
        }
        String userUrl = mUser.getLogoUrl();
        Glide.with(mContext).load(userUrl).placeholder(R.drawable.ic_default_avatar).transform(new GlideCircleTransform(mContext)).into(mImAvatar);
        mTvName.setText(mUser.getUserName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_change_password:
                Bundle bundle = new Bundle();
                bundle.putString("userId", mUserId);
                startActivity(ChangePasswordActivity.class, bundle);
                break;
            case R.id.im_avatar:
                DialogUtil.showUploadFile(mContext, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        getImageFromCamera();
                    }
                }, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        selectImageFromAlbum();
                    }
                });
                break;
            case R.id.layout_download_list:
                startActivityWithIntent(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
                break;
            case R.id.rl_exit:
                DialogUtil.showSimpleAlertDialog(mContext, new DialogOnClick() {
                    @Override
                    public void onClick(Object o) {
                        app.setUser(null);
                        spUtil.putString("user", "");
                        app.loginOut();
                        MiPushClient.setAlias(mContext, "", null);
                        startActivity(LoginActivity.class);
                    }
                }, "是否退出登录");
                break;
            default:
                break;
        }
    }

    /***
     * 拍照
     */
    private void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        mUpdateIconCameraPath = Constants.Const_Cache_Dir + System.currentTimeMillis() + ".png";
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir = new File(Constants.Const_Cache_Dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(mUpdateIconCameraPath);//localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, Constants.REQUESTCODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(mContext, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册选择
     */
    private void selectImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, Constants.REQUESTCODE_ALBUM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUESTCODE_CAPTURE_CAMEIA:
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = Uri.fromFile(new File(mUpdateIconCameraPath));
                    initCrope(uri);
//                    ClipImageActivity.startActivity(this, mUpdateIconCameraPath, Constants.REQUESTCODE_CHOOSE_PIC);
//
                }
                break;
            case Constants.REQUESTCODE_ALBUM:
                if (resultCode == Activity.RESULT_OK) {
                    mUpdateIconCameraPath = data.getData().getPath();
                    if (FileUtil.checkFileByType(mUpdateIconCameraPath, "img")) {

                    } else {
                        Uri uri = data.getData();
                        mUpdateIconCameraPath = getRealPathFromURI(uri);
                    }
                    Uri uri = Uri.fromFile(new File(mUpdateIconCameraPath));
                    initCrope(uri);
                }
                break;
            case Constants.REQUESTCODE_CHOOSE_PIC:
                if (data != null) {
                    Bitmap bmap = data.getParcelableExtra("data");
                    saveBitmapFile(bmap);
                    Glide.with(mContext).load(mUpdateIconCameraPath).transform(new GlideCircleTransform(mContext)).into(mImAvatar);
                    updateOss(app.getOss(), mUpdateIconCameraPath);
                }
                break;
            default:
                break;
        }
    }

    private void initCrope(Uri imageUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.REQUESTCODE_CHOOSE_PIC);
    }

    private String getRealPathFromURI(Uri contentUri) { //传入图片uri地址
        String path = "";
        Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();
            cursor = mContext.getContentResolver().query(
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
            if (cursor != null) {
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
            }
        }
        return path;
    }

    public void saveBitmapFile(Bitmap bitmap) {
        File file = new File(mUpdateIconCameraPath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateOss(final OSS oss, final String path) {
        mUser = app.getUser();
        if (mUser == null) {
            ToastOpt.createToast(mContext, "请先登陆");
            return;
        }
        DialogUtil.showLoadDiadlog(mContext);
        // 指定数据类型，没有指定会自动根据后缀名判断
        new Thread(new Runnable() {
            @Override
            public void run() {
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentType("image/jpeg");
                Random random = new Random(1000);//指定种子数字
                final String name = System.currentTimeMillis() + random.nextInt() + ".png";
                // 构造上传请求
                PutObjectRequest put = new PutObjectRequest("yirimao", name, path);
                put.setMetadata(objectMeta);
                try {
                    PutObjectResult putObjectResult = oss.putObject(put);
                } catch (ClientException
                        e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }

                // 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        // 在这里可以实现进度条展现功能
                        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                    }
                });
                OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        HashMap<String, String> params = new HashMap<String, String>();
                        String token = mUser.getToken();
                        final String logoUrl = Constants.OSS_ENDPOINT + "/" + name;
                        params.put("token", token);
                        params.put("logoUrl", logoUrl);
                        mManager.post(NetworkAPI.UpdateFile, new HttpCallback() {
                            @Override
                            public void onSuccess(int code, String value, String msg) {
                                ToastOpt.createToast(mContext, "图片上传成功");
                                mUser.setLogoUrl(logoUrl);
                                spUtil.putString("user", new Gson().toJson(mUser));
                                app.setUser(mUser);
                                DialogUtil.dismiss(mContext);
                            }

                            @Override
                            public void onFailure(String value) {
                                ToastOpt.createToast(mContext, "图片上传失败");
                                Glide.with(mContext).load(mUser.getLogoUrl()).placeholder(R.drawable.ic_default_avatar).transform(new GlideCircleTransform(mContext)).into(mImAvatar);
                                DialogUtil.dismiss(mContext);
                            }
                        }, params);

                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        Glide.with(mContext).load(mUser.getLogoUrl()).placeholder(R.drawable.ic_default_avatar).transform(new GlideCircleTransform(mContext)).into(mImAvatar);
                        DialogUtil.dismiss(mContext);
                        ToastOpt.createToast(mContext, "图片上传失败，请重新上传");
                        return;
                    }
                });
            }
        }).start();

    }

    public void hasPermissionInManifest(Context context, String permissionName) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                5);
    }
}
